<?php

namespace app\common\library;

use think\Config;
use think\Exception;
use Tx\Mailer;
use Tx\Mailer\Exceptions\CodeException;
use Tx\Mailer\Exceptions\SendException;

/**
 * 蒙古Qpay支付类
 * @classname Qpay
 * @package app\common\library
 */
class Qpay
{

    public string $url;//支付url
    public string $userName;//用户名
    public string $password;//密码
    public string $basic;//basic

    public function __construct()
    {
        $this->url      = config('site.qpay_url');
        $this->userName = config('site.qpay_username');
        $this->password = config('site.qpay_password');
        $this->basic    = 'VEVTVF9NRVJDSEFOVDoxMjM0NTY=';
    }

    /**
     * 获取token
     */
    public function getAccessToken() {
        $url = $this->url."/v2/auth/token";
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_USERPWD, "$this->userName:$this->password");
//        curl_setopt($ch, CURLOPT_HTTPHEADER, ["Authorization: Basic ".$this->basic]);
        $response = curl_exec($ch);
        curl_close($ch);
        $res = json_decode($response, true);
        if(!empty($res['refresh_expires_in'])){
            $token = $res['access_token'];
        }
       return $token;
    }

    /**
     * 2. 刷新访问令牌
     * @param $token
     * @return mixed
     */
    public function refreshToken($token) {
        $url = $this->url."/v2/auth/refresh";
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_HTTPHEADER, [
            "Authorization: Bearer $token"
        ]);

        $response = curl_exec($ch);
        curl_close($ch);
        return json_decode($response, true);
    }

    /**
     * 创建订单
     * @param $data
     * @return mixed
     */
    public  function invoice($data) {
        // 1. 构建请求 URL 和 JSON 数据
        return $this->sendRequest('POST','/v2/invoice',$data);
    }


    /**
     * 公共请求
     * @param $method
     * @param $endpoint
     * @param null $data
     * @param bool $isJson
     * @return array
     */

    public function sendRequest($method, $endpoint, $data = null, $isJson = true): array
    {
        $url = $this->url . $endpoint;
        $ch = curl_init($url);

        $headers = ["Authorization: Bearer " . $this->getAccessToken()];
        if ($isJson) {
            $headers[] = "Content-Type: application/json";
        }

        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

        if ($data) {
            curl_setopt($ch, CURLOPT_POSTFIELDS, $isJson ? json_encode($data) : $data);
        }

        $response = curl_exec($ch);
        $status = curl_getinfo($ch, CURLINFO_HTTP_CODE);

        return [
            'status' => $status,
            'body' => json_decode($response, true) ?: $response
        ];
    }

    /**
     * 获取订单支付信息
     * @param $data
     * @return mixed
     */
    public function orderCheck($data){
        return $this->sendRequest("POST",'/v2/payment/check',$data);
    }

    /**
     * 获取订单支付信息
     * @param $data
     * @return mixed
     */
    public function payment($orderId){
        return $this->sendRequest('GET','/v2/payment/'.$orderId);
    }
}
